package com.etalk.crm.serviceImpl;

import com.etalk.crm.dao.ClassChangeAutoRecordMapper;
import com.etalk.crm.dao.LessonsMapper;
import com.etalk.crm.pojo.ClassChangeAutoRecord;
import com.etalk.crm.pojo.LessonResult;
import com.etalk.crm.service.ClassChangeAutoRecordService;
import com.etalk.crm.utils.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.*;

/**
 * @Author Jordan
 * @Date 2020/12/15 14:05
 * @Version 1.0
 */
@Service
public class ClassChangeAutoRecordServiceImpl implements ClassChangeAutoRecordService {
    private static final Logger logger = LogManager.getLogger(ClassChangeAutoRecordServiceImpl.class);

    @Resource
    private ClassChangeAutoRecordMapper classChangeAutoRecordMapper;
    @Resource
    private LessonsMapper lessonsMapper;
    @Resource
    private HttpSession session;

    /**
     * 自动调课分页列表
     * @param record 查询条件
     * @param pageNum 页码
     * @param pageSize 页记录数
     * @return
     */
    @Override
    public PageInfo<ClassChangeAutoRecord> searchClassChangeAutoRecordListByPage(ClassChangeAutoRecord record,Integer pageNum,Integer pageSize){
        if (pageNum == null) {
            pageNum=1;
        }
        if (pageSize == null){
            pageSize=20;
        }

        PageHelper.startPage(pageNum,pageSize);

        List<ClassChangeAutoRecord> list=classChangeAutoRecordMapper.selectClassChangeAutoRecordList(record);

        return new PageInfo<>(list);
    }

    /**
     * 添加自动调课记录
     * @param lessonId 课程id
     * @return
     */
    @Override
    public Map<String, Object> addClassChangeAutoRecord(Integer lessonId,String newReleaseTime,Integer reasonId) {
        Map<String,Object> resultMap=new HashMap<>(2);
        if (lessonId==null){
            resultMap.put("status",0);
            resultMap.put("errMsg","课程id不能为空");
            return resultMap;
        }
        LessonResult result= lessonsMapper.selectChangeAutoLessonInfoByLessonId(lessonId);
        if (result == null || result.getLessonId()==null){
            resultMap.put("status",0);
            resultMap.put("errMsg","课程不存在或状态已发生改变");
            return resultMap;
        }
        int beforeMin=-1;
        if (DateUtils.addMinutes(result.getReleaseTime(),beforeMin).getTime() < DateUtil.getTime()){
            resultMap.put("status",0);
            resultMap.put("errMsg","距离上课开始前"+beforeMin+"分钟内，不能加入自动调课");
            return resultMap;
        }
        ClassChangeAutoRecord record=new ClassChangeAutoRecord();

        Date classDate= null;
        try {
            if (StringUtils.isNotEmpty(newReleaseTime)) {
                String[] patterns=new String[] {"yyyy-MM-dd HH:mm:ss"};
                classDate = DateUtils.parseDate(newReleaseTime, patterns);
            }
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
            resultMap.put("status",0);
            resultMap.put("errMsg","调课日期格式错误");
            return resultMap;
        }
        record.setLessonId(result.getLessonId())
                .setTeacher(result.getTeacherLogin())
                .setReleaseTime(result.getReleaseTime())
                .setOrderId(result.getOrderId())
                .setStudentId(result.getPersonId())
                .setNewReleaseTime(classDate)
                .setReasonId(reasonId)
                .setCreateTime(new Date())
                .setCreator(session.getAttribute("loginname").toString());
        if (classChangeAutoRecordMapper.countClassChangeAutoRecord(record)>0){
            resultMap.put("status",0);
            resultMap.put("errMsg","已加入自动调课计划");
            return resultMap;
        }
        int num=classChangeAutoRecordMapper.insertClassChangeAutoRecord(record);
        if (num > 0){
            resultMap.put("status",1);
        }else {
            resultMap.put("status",0);
            resultMap.put("errMsg","添加自动调课记录失败");
        }
        return resultMap;
    }

    /**
     * 批量添加自动调课计划记录
     * @param listLessonId 课程id数组
     * @param reasonId 调课原因id
     * @return
     */
    @Override
    public Map<String, Object> batchAddClassChangeAutoRecord(List<Integer> listLessonId, Integer reasonId) {
        Map<String,Object> resultMap=new HashMap<>(2);
        if (listLessonId==null || listLessonId.size()==0){
            resultMap.put("status",0);
            resultMap.put("errMsg","课程id不能为空");
            return resultMap;
        }
        List<LessonResult> listResult= lessonsMapper.selectChangeAutoLessonInfo(listLessonId);
        if (listResult == null || listResult.size()==0){
            resultMap.put("status",0);
            resultMap.put("errMsg","课程不存在或状态已发生改变");
            return resultMap;
        }

        List<ClassChangeAutoRecord> listAdd=new ArrayList<>();
        int beforeMin=-1;
        for (LessonResult result:listResult){
            if (DateUtils.addMinutes(result.getReleaseTime(),beforeMin).getTime() < DateUtil.getTime()){
                //课前beforeMin分钟不能添加到自动调课
                continue;
            }
            ClassChangeAutoRecord record=new ClassChangeAutoRecord();
            record.setLessonId(result.getLessonId())
                    .setTeacher(result.getTeacherLogin())
                    .setReleaseTime(result.getReleaseTime())
                    .setOrderId(result.getOrderId())
                    .setStudentId(result.getPersonId())
                    .setNewReleaseTime(result.getReleaseTime())
                    .setReasonId(reasonId)
                    .setCreateTime(new Date())
                    .setCreator(session.getAttribute("loginname").toString());
            if (classChangeAutoRecordMapper.countClassChangeAutoRecord(record)==0){
                listAdd.add(record);
            }
        }
        if (listAdd.size()==0){
            resultMap.put("status",0);
            resultMap.put("errMsg","没有可调的课程或课程已加入自动调课计划");
            return resultMap;
        }
        if (listAdd.size()>0){
            int num=classChangeAutoRecordMapper.batchInsertClassChangeAutoRecord(listAdd);
            if (num > 0){
                resultMap.put("status",1);
                if (listLessonId.size()==num){
                    resultMap.put("msg","添加自动调课记录成功");
                }else {
                    resultMap.put("msg", "添加自动调课记录成功" + num + ",失败"+(listLessonId.size()-num));
                }
            }else {
                resultMap.put("status",0);
                resultMap.put("errMsg","添加自动调课记录失败");
            }
        }

        return resultMap;
    }

    /**
     * 取消调课计划
     * @param id 调课计划id
     * @return
     */
    @Override
    public Map<String, Object> cancelClassChangeAutoRecordById(int id){
        Map<String,Object> resultMap=new HashMap<>(2);
        int num=classChangeAutoRecordMapper.delClassChangeAutoRecordById(id);
        if (num>0){
            resultMap.put("status",1);
        }else {
            resultMap.put("status",0);
            resultMap.put("errMsg","删除自动调课记录失败");
        }
        return resultMap;
    }

    /**
     * 批量删除自动调课记录
     * @param listId 调课记录id
     * @return
     */
    @Override
    public Map<String, Object> cancelClassChangeAutoRecordById(List<Integer> listId){
        Map<String,Object> resultMap=new HashMap<>(2);
        int num=classChangeAutoRecordMapper.delClassChangeAutoRecordByIds(listId);
        if (num>0){
            resultMap.put("status",1);
            resultMap.put("msg", "删除自动调课记录成功" + num + ",失败"+(listId.size()-num));
        }else {
            resultMap.put("status",0);
            resultMap.put("errMsg","删除自动调课记录失败");
        }
        return resultMap;
    }
}
